
import { useCounterStore } from '../stores/counter'

interface messageData{
  type: string,
  msg:string
}
class mySocket {
   static scoketData:any ;
   static socketOpen:boolean = false;

// 断开连接时，存储的消息
    static socketMsgQueue:any[] = [];
    static timer:any
    // 创建scoket
   static  create(){
        
const counter = useCounterStore()
    

console.log('创建中');

        uni.connectSocket({
          url: 'wss://www.sanheiot1993.com/api/m/iot/list',
          // url: 'ws://192.168.173.76:10003/api/m/iot/list',
          header: {
            'Authorization':counter.token,
            'content-type': 'application/json'
          },
         
        });
        
        
    };
    // 监听Socket打开事件
    static onSocketOpen(){
        uni.onSocketOpen( (res:any)=> {
            console.log('WebSocket连接已打开！');
          mySocket.socketOpen = true;
          mySocket.onSocketMessage()
          const counter = useCounterStore()
          mySocket.sendSocketMessage(counter.dizhi)
          });
        
    }
    // 监听WebSocket错误。
    static onSocketError(){
        uni.onSocketError( (res)=> {
          // mySocket.create()
          console.log('WebSocket连接打开失败，请检查！');

 mySocket.reconnect(); // 连接关闭后尝试重连
     
     
          });
    }

    // 发送消息
    static sendSocketMessage(msg:any) {
   
        if (mySocket.socketOpen) {

          console.log('发送中');
          
let da = JSON.stringify(
  {
    type:'search',
    msg
  }
)

          uni.sendSocketMessage({
           
            data:da
          });

          
          
        } else {
          mySocket.socketMsgQueue.push(msg);
        }
      }

    //   接收事件
    static  onSocketMessage(){
      const counter = useCounterStore()
      uni.onSocketMessage( (res)=> {
    
    
       counter.instShouData(JSON.parse(res.data as string));
  console.log("收到后端信息");

        });

        
    
    }
// 关闭socket链接
static  closeSocket(){

        if(mySocket.socketOpen){
            uni.closeSocket();
            
        }
       
    }
    // 关闭事件
    static  onSocketClose(){
        uni.onSocketClose( (res:any)=> {

            console.log('WebSocket 已关闭！');
            mySocket.socketOpen=false
            mySocket.reconnect();
          });
    }

        // 关闭事件
        static  onSocketCloseyonh(){

          this.closeSocket()
          uni.onSocketClose( (res:any)=> {
  
              console.log('WebSocket永久 已关闭！');
              mySocket.socketOpen=false
            });
      }
    // 重连
    static reconnect() {
      if (!mySocket.socketOpen) {
          mySocket.timer = setTimeout(() => {
              console.log('尝试重新连接 WebSocket...');
              mySocket.create();
          }, 2000); // 每隔5秒尝试重新连接
      }
  }
 
    }


    
    export default mySocket